﻿using System;
using System.Collections.Generic;
using Needle.Bus.Messages;

namespace Needle.Bus.Engine
{

    internal class SinkTransaction : IDisposable
    {
        /// <summary>
        /// Initializes a new instance of the SinkTransaction class.
        /// </summary>
        /// <param name="sink"></param>
        /// <param name="messages"></param>
        public SinkTransaction(ISink sink, IList<IMessage> messages)
        {
            _sink = sink;
            _sinkId= sink.Id;
            _messages = messages;
        }

        IList<IMessage> _messages;
        private bool _completed;
        private readonly string _sinkId;

        ISink _sink;
        public ISink Sink
        {
            get { return _sink; }
        }

        public void Commit()
        {
            ISink sink = _sink;
            IList<IMessage> messages = _messages;
            SetCompleted();
            sink.Enqueue(messages);
        }

        public void Abort()
        {
            SetCompleted();
        }

        void IDisposable.Dispose()
        {
            if (!_completed)
                SetCompleted();
        }

        private void SetCompleted()
        {
            if (_completed)
                throw new InvalidOperationException("Transaction already completed");
            _completed = true;
            _sink = null;
            _messages = null;
        }

        public override string ToString()
        {
            return String.Format("SinkTransaction for sink {0}", _sinkId);
        }

    }
}
